#!/bin/bash
# 设备证书自动化生成与部署脚本（带密码自动输入）
# 使用说明：./autoca.sh <设备名> <设备IP> <设备用户>

# 检查参数数量
if [ $# -ne 3 ]; then
    echo "错误：参数不正确！用法: $0 <设备名> <设备IP> <设备用户>"
    exit 1
fi

# 1. 定义变量
device="$1"
device_ip="$2"
device_user="$3"

# 2. 交互式输入密码
read -s -p "请输入本机sudo的密码: " sudo_pass
echo
read -s -p "请输入CA的密码: " ca_pass
echo
read -s -p "请输入远程设备($device_ip)的密码: " remote_pass
echo

# 证书目录配置 
csr_dir="/etc/ssl/csr"
private_dir="/etc/ssl/private"
certs_dir="/etc/ssl/certs"
ca_cert_path="/etc/ssl/ca/certs/ca.cert.pem"

# 2. 创建私钥
echo "正在为 $device 生成2048位RSA私钥..."
sudo openssl genrsa -out "$csr_dir/$device.key" 2048
if [ $? -ne 0 ]; then
    echo "错误：私钥生成失败"
    exit 1
fi
sudo chmod 600 "$csr_dir/$device.key"

# 3. 创建CSR配置文件
config_file="$csr_dir/$device.csr.cnf"
echo "生成CSR配置文件: $config_file"
sudo tee "$config_file" > /dev/null <<EOF
[ req ]
prompt = no
distinguished_name = req_distinguished_name
req_extensions = v3_req

[ req_distinguished_name ]
countryName = CN
stateOrProvinceName = GuangDong
localityName = ShenZhen
organizationName = Aixot
organizationalUnitName = Aixot Yanfa
commonName = $device.local
emailAddress = sales@aixot.com

[ v3_req ]
basicConstraints = CA:FALSE
keyUsage = digitalSignature, keyEncipherment
subjectAltName = @alt_names

[ alt_names ]
DNS.1 = $device.local
DNS.2 = $device
IP.1 = 119.91.155.2
EOF

# 4. 生成CSR文件
echo "生成证书签名请求(CSR)..."
sudo openssl req -new -key "$csr_dir/$device.key" \
    -out "$csr_dir/$device.csr" \
    -config "$config_file"
if [ $? -ne 0 ]; then
    echo "错误：CSR生成失败"
    exit 1
fi

# 5. 使用CA签署证书（自动输入CA密码）
echo "CA签署证书中..."
expect <<EOF
  set timeout 30
  spawn sudo openssl ca -config /etc/ssl/ca/openssl.cnf \
      -extensions v3_req -days 365 -notext -md sha256 \
      -in "$csr_dir/$device.csr" -out "$csr_dir/$device.crt"
  expect {
    "*的密码" {
      send "$sudo_pass\r"
      exp_continue
    }
    "yes/no?" {
      send "yes\r"
      exp_continue
    }
    "y/n?" {
      send "y\r"
      exp_continue
    }
    "Enter pass phrase for" {
      send "$ca_pass\r"
      exp_continue
    }
    "Sign the certificate?" {
      send "y\r"
      exp_continue
    }
    "certificate requests certified, commit?" {
      send "y\r"
    }
    timeout {
      send_user "\n错误：操作超时\n"
      exit 1
    }
    eof
  }
EOF
# 验证结果
if [ -f "$csr_dir/$device.crt" ]; then
  echo "✓ 证书签署成功"
else
  echo "✗ 证书签署失败"
  exit 1
fi

# 6. 合成证书链 
chain_file="$csr_dir/$device-chain.pem"
echo "合成证书链文件: $chain_file"
sudo cat "$csr_dir/$device.crt" "$ca_cert_path" | sudo tee "$chain_file" > /dev/null

# 7. SCP传输文件到目标设备（使用密码自动登录）
# 使用expect处理SCP密码交互
expect <<EOF
  set timeout 15
  spawn sudo scp -o StrictHostKeyChecking=no \
    $csr_dir/$device.crt \
    $chain_file \
    $ca_cert_path \
    $device_user@$device_ip:$certs_dir/
  expect {
    "*的密码" {
      send "$sudo_pass\r"
      exp_continue
    }
    "y/n" {
      send "y\r"
      exp_continue
    }
    "yes/no" {
      send "yes\r"
      exp_continue
    }
    "password" {
      send "$remote_pass\r"
      exp_continue
    }
    timeout {
      send_user "\n错误：操作超时\n"
      exit 1
    }
    eof
  }
EOF

expect <<EOF
  set timeout 15
  spawn sudo scp -o StrictHostKeyChecking=no \
    $csr_dir/$device.key \
    $device_user@$device_ip:$private_dir/
  expect {
    "*的密码" {
      send "$sudo_pass\r"
      exp_continue
    }
    "y/n" {
      send "y\r"
      exp_continue
    }
    "yes/no" {
      send "yes\r"
      exp_continue
    }
    "password" {
      send "$remote_pass\r"
      exp_continue
    }
    timeout {
      send_user "\n错误：操作超时\n"
      exit 1
    }
    eof
  }
EOF

echo "===== 证书部署流程完成 ====="